import axios from 'axios';
import _Vue from '../../main';
import router from '../../router';
import store from '../../store';

const baseURL = CONFIG.baseURL;
axios.defaults.withCredentials = true;//让ajax携带cookie
const request = axios.create({
    baseURL: baseURL, // api 的 base_url
    timeout: 5000000 // request timeout
})

// 添加请求拦截器
request.interceptors.request.use(config => {
    //请求统一增加请求头
    config.headers["Content-Type"] = "application/json"
    config.headers.common = {
        "Authorization": _Vue.getStorage("authorization") || "",
        "client-name": "base_cloud",
        "program-id": _Vue.$store.state.programId,
    }
    return config;
})

//添加响应拦截器
request.interceptors.response.use(res => { //成功返回
    //文件流下载
    if (res.config.responseType === 'arraybuffer') {
        let info = JSON.parse(res.headers.fileinfo);
        if (info.code === "50") {
            return Promise.reject(info);
        }
        info = Object.assign(res.data, res.headers);
        return Promise.resolve(info);
    } else {
        if (res.data) {
            if (res.data.code === "1") {//成功返回
                return Promise.resolve(res.data)
            } else {
                _Vue.$message.error(res.data.message);
                if (res.data.code == "2") {//未登录
                    localStorage.clear();
                    router.push('/');
                } else if (res.data.code == '3') { //没有权限
                    store.state.refreshMenu = true;
                } else if (res.data.code === '4') { //不能访问
                    localStorage.clear();
                    router.push('/');
                }
                return Promise.reject(res.data)
            }
        } else {
            if (res.data.message) {
                _Vue.$message.error(res.data.message);
            }
            return Promise.reject(res.data);
        }
    }
}, error => { //失败返回，方法返回一个带有拒绝原因reason参数的Promise对象。
    _Vue.$message.error(error.toString());
    return Promise.reject(error);
})

function get(url, data, responseType) {
    return request.get(url, {
        params: data,
        responseType: responseType,
        onDownloadProgress(e) {
            if (this.responseType == 'arraybuffer' && e.total) {
                if (!_Vue.$uProgress.showToast) {
                    _Vue.$uProgress.show();
                }
                _Vue.$uProgress.percentage = Math.round(e.loaded / e.total * 100);
            }
        }
    })
}

function post(url, data, responseType) {
    return request.post(url, data, {
        responseType: responseType,
        onDownloadProgress(e) {
            if (this.responseType == 'arraybuffer' && e.total) {
                if (!_Vue.$uProgress.showToast) {
                    _Vue.$uProgress.show();
                }
                _Vue.$uProgress.percentage = Math.round(e.loaded / e.total * 100);
            }
        }
    })
}

export default {
    get, post
}